<?php

require_once "lib/controller.php";

class UserController extends BaseController {
	
	public function index($route)
	{
		include("lib/config.php");
		include("conf/routes.php");
		$con = mysql_connect($db_server,$db_user,$db_password);
		if (!$con)
		{
			die('Could not connect: ' .mysql_error());
		}
		mysql_select_db($db_name) or die(mysql_error());

		if(isset($_POST["day"]) && isset($_POST["month"]) && isset($_POST["year"])){
			// We got a request for a specific date
			$day = (int)mysql_real_escape_string($_POST["day"]);
			$month = (int)mysql_real_escape_string($_POST["month"]);
			$year = (int)mysql_real_escape_string($_POST["year"]);
		} else {
			//No specific date, just use today
			$day = (int) date("j");
			$month = (int) date("n");
			$year = (int) date("Y");
		}
		
		if(isset($_POST["residence"])){
			// We got a request for a residence
			$residence = mysql_real_escape_string($_POST["residence"]);
		} else {
			//No specific residence, just use residence A
			$residence = 'A';
		}
		

		$userId = $this->isConnected();
		if($userId >= 0){
			//user is logged in
			$req = mysql_query("SELECT * FROM Users WHERE id_user=".strval($userId));
			$data = mysql_fetch_array($req);

			$username = $data['name'];
		} else {
			$username = "";
		}

			
		$req = mysql_query(sprintf("SELECT COUNT(id_machine) FROM Machines WHERE Residence = '%s'", $residence));
		$data = mysql_fetch_array($req);
		$nbMachine = (int)$data['COUNT(id_machine)'];
		
		$req = mysql_query(sprintf("SELECT * FROM Machines WHERE Residence = '%s'", $residence));
		for($i=0; $i<$nbMachine; $i++){
			$av = array();

			$data = mysql_fetch_array($req);
			$currentIdMachine = (int) $data['id_machine'];

			for($currentHour = 0; $currentHour < 24; $currentHour++ ){
				if($data['state'] == 'working'){ // Machine is working
					$req1 = mysql_query(sprintf("SELECT COUNT(id_booking) FROM Bookings WHERE ( id_machine = %d AND year = %d AND month = %d AND day=%d AND hour=%d); ", $currentIdMachine, $year, $month, $day, $currentHour)) or die(mysql_error());

					$data1 = mysql_fetch_array($req1);
					$nbBookings = (int) $data1['COUNT(id_booking)'];

					if($nbBookings > 0){
						$req2 = mysql_query(sprintf("SELECT * FROM Bookings WHERE ( id_machine = %d AND year = %d AND month = %d AND day=%d AND hour=%d); ", $currentIdMachine, $year, $month, $day, $currentHour)) or die(mysql_error());
						$data2 = mysql_fetch_array($req2);
						if((int)$data2['id_user'] == $this->isConnected() ){
							$av[$currentHour] = 3; //Occupe par l'utilisateur courant
						} else {
							$av[$currentHour] = 1; // Occupe par quelqu'un
						}
					} else {
						//echo("empty.");
						$av[$currentHour] = 0; // Libre
					}
				} else {
					$av[$currentHour] = 2; // Failure
				}
			}
			$av['isReported'] = $data['isReported'];
			$availability[] = $av;
		}
		$admin = false;
		if ($this->isAdmin()) {
		  $admin = true;
		}
		
		
		//Render the page according to processed parameters
        $this->render_view("index", array("controller" => "user", "day" => $day, "month" => $month, "year" => $year, "username" => $username, "nbMachine" => $nbMachine, "residence" => $residence, "availability" => $availability, "admin" => $admin ));
	}
	
	public function addBooking($route)
	{
		$user = $this->isConnected();
		if (isset($_POST["machine"]) && isset($_POST["year"]) && isset($_POST["month"]) && isset($_POST["day"]) && isset($_POST["hour"]) && isset($_POST["residence"]) && ($user != -1)) {
			
			include("lib/config.php");
			$con = mysql_connect($db_server,$db_user,$db_password);
			if (!$con)
			{
				die('Could not connect: ' .mysql_error());
			}
			mysql_select_db($db_name) or die(mysql_error());

			//BEWARE : Machine number and hour are not the same between JS and SQL !
			$req = mysql_query(sprintf("SELECT * FROM Machines WHERE Residence = '%s'", $_POST["residence"]));
			for($i=0; $i<(int)$_POST["machine"]; $i++){
				$data = mysql_fetch_array($req);
			}
			$machine_id = $data['id_machine'];

			// Is he allowed to book another ? => TODO
			$isAllowed = true;
			// First : count day's bookings for user
			$req1 = mysql_query(sprintf("SELECT COUNT(id_booking) FROM Bookings WHERE ( id_user = %d AND day = %d AND month = %d AND year = %d); ", $user, $_POST["day"], $_POST["month"], $_POST["year"])) or die(mysql_error());
			$data1 = mysql_fetch_array($req1);
			$nbBookings = (int) $data1['COUNT(id_booking)'];
			if($nbBookings > 3){
				$isAllowed = false;
			}
			
			// Then : count hour's bookings for user
			$req1 = mysql_query(sprintf("SELECT COUNT(id_booking) FROM Bookings WHERE ( id_user = %d AND day = %d AND month = %d AND year = %d AND hour = %d); ", $user, $_POST["day"], $_POST["month"], $_POST["year"], $_POST["hour"])) or die(mysql_error());
			$data1 = mysql_fetch_array($req1);
			$nbBookings = (int) $data1['COUNT(id_booking)'];
			if($nbBookings > 1){
				$isAllowed = false;
			}				
			
			if($isAllowed){
				$sql_query = sprintf("INSERT INTO Bookings ( id_machine, id_user, year, month, day, hour) VALUES (%d, %d, %s, %s, %s, %s)",$machine_id,$user,mysql_real_escape_string($_POST["year"]),mysql_real_escape_string($_POST["month"]),mysql_real_escape_string($_POST["day"]),mysql_real_escape_string($_POST["hour"]));
				mysql_query($sql_query) or die(mysql_error());
				$this->index($route);
			} else {
				$this->render_error("error", "Too many bookings from you", $route);
			}
		} else {
			$this->render_error("error", "Not Identified request. You should log in first.", $route);
        }
	}
	
	public function cancelBooking($route)
	{
		$user = $this->isConnected();
		if (isset($_POST["machine"]) && isset($_POST["year"]) && isset($_POST["month"]) && isset($_POST["day"]) && isset($_POST["hour"]) && $user != -1) {
			include("lib/config.php");
			$con = mysql_connect($db_server,$db_user,$db_password);
			if (!$con)
			{
				die('Could not connect: ' .mysql_error());
			}
			mysql_select_db($db_name) or die(mysql_error());
			 
			//BEWARE : Machine number and hour are not the same between JS and SQL !
			$req = mysql_query(sprintf("SELECT * FROM Machines WHERE Residence = '%s'", $_POST["residence"]));
			for($i=0; $i<(int)$_POST["machine"]; $i++){
				$data = mysql_fetch_array($req);
			}
			$machine_id = $data['id_machine'];

			$reqSql = sprintf("DELETE FROM Bookings WHERE id_machine = %d AND id_user = %d AND year = %s AND month = %s AND day = %s AND hour = %s",$machine_id,$user,mysql_real_escape_string($_POST["year"]),mysql_real_escape_string($_POST["month"]),mysql_real_escape_string($_POST["day"]),mysql_real_escape_string($_POST["hour"]));
			mysql_query($reqSql) or die(mysql_error());
			$this->index($route);
		} else {
			$this->render_error("400", "Not Identified request. You should log in first.", $route);
        }
        
	}	
	
	public function reportFailure($route)
	{
		$user = $this->isConnected();
		if (isset($_POST["machine"]) && isset($_POST["residence"]) && ($user != -1)) {
			
			include("lib/config.php");
			$con = mysql_connect($db_server,$db_user,$db_password);
			if (!$con)
			{
				die('Could not connect: ' .mysql_error());
			}
			mysql_select_db($db_name) or die(mysql_error());

			//BEWARE : Machine number and hour are not the same between JS and SQL !
			$req = mysql_query(sprintf("SELECT * FROM Machines WHERE Residence = '%s'", $_POST["residence"])) or die(mysql_error());
			for($i=0; $i<(int)$_POST["machine"]; $i++){
				$data = mysql_fetch_array($req);
			}
			$machine_id = $data['id_machine'];


			//Send mails to admins
			$result = mysql_query("SELECT * FROM Users WHERE is_admin = 1") or die(mysql_error());
			
			while($r = mysql_fetch_array($result)) {
				$mailTo = $r["mail"];
				$msgSubject = "Machine Failure Report";
				$msgBody = "The following machine has been reported to be failing : " . $_POST["machine"]." by user : " . $user ;
				mail ($mailTo, $msgSubject, $msgBody);
			}

			// Set as reported in database
			$query = sprintf("UPDATE Machines SET isReported=true WHERE id_machine =%d",$machine_id);
			mysql_query($query) or die(mysql_error());

			$this->render_error("success", "Failure report has been mailed to admins. Thanks for your help !", $route);

		} else {
			$this->render_error("error", "Not Identified request. You should log in first.", $route);
        }
	}

	
	public function showProfile($route)
	{
		$user = $this->isConnected();
		if ($user != -1) {
      include("lib/config.php");
			mysql_connect($db_server, $db_user, $db_password) or die(mysql_error());
			mysql_select_db($db_name) or die(mysql_error());
			
			$result = mysql_query(sprintf("SELECT * FROM Users WHERE id_user='%s'", $user));
			
			$r = mysql_fetch_array($result);

            $admin = false;
			if ($this->isAdmin()) {
			  $admin = true;
			}
			
			$this->render_view("profile", array("controller" => "user", "id_user" => $r['id_user'], "name" => $r['name'], "mail" => $r['mail'], "admin" => $admin));
		}
	}
	
	public function modifyMail($route)
	{
		$user = $this->isConnected();
		if (isset($_POST["mail"]) && $user != -1) {
			include("lib/config.php");	
			$con = mysql_connect($db_server,$db_user,$db_password);
			if (!$con)
			{
				die('Could not connect: ' .mysql_error());
			}
			mysql_select_db($db_name) or die(mysql_error());
			 
			$enr = mysql_query(sprintf("UPDATE Users SET mail='%s' WHERE id_user='%s'",mysql_real_escape_string($_POST["mail"]),$user));
			
			if ($enr==true){ 
              echo "Mail modifié"; //à modifier
            } 
            else { 
              echo mysql_error(); 
            } 
			
		} else {
          $this->render_error("error", "Not Identified request. You should log in first.", $route);
        }
	}
	
	public function modifyPassword($route)
	{
		$user = $this->isConnected();
		if (isset($_POST["newPassword"]) && $user != -1) {
			include("lib/config.php");
			$con = mysql_connect($db_server,$db_user,$db_password);
			if (!$con)
			{
				die('Could not connect: ' .mysql_error());
			}
			mysql_select_db($db_name) or die(mysql_error());
      $userName = mysql_query(sprintf("SELECT name FROM Users WHERE id_user=%d", $user));
      $name = mysql_fetch_array($userName);
			$hash = hash("sha512", $name['name'].$_POST["newPassword"]);

			$enr = mysql_query(sprintf("UPDATE Users SET password_hash='%s' WHERE id_user=%d", $hash, $user)) or die(mysql_error());
			
			if ($enr==true){ 
              echo "Mot de passe modifié";//à modifier
            } 
            else { 
              echo mysql_error(); 
            } 
			
		} else {
          $this->render_error("error", "Not Identified request. You should log in first.", $route);
        }
	}
  
  public function modify($route) {
    $user = $this->isConnected();
    if($user != -1){
        include("conf/routes.php");
        include("lib/config.php");
        mysql_connect($db_server, $db_user, $db_password) or die(mysql_error());
        mysql_select_db($db_name) or die(mysql_error());
        
        $result = mysql_query(sprintf("SELECT * FROM Users WHERE id_user='%s'", $user));
        
        $r = mysql_fetch_array($result);

        $this->render_view("modify",array("controller" => "user", "id_user" => $r['id_user'], "name" => $r['name'], "mail" => $r['mail']));
      } else {
        $this->render_error("error", "Not Identified request. You should log in first.", $route);
      }
  }

	public function login($route){
		if(isset($_POST["pseudo"]) && isset($_POST['motdepasse'])){
			$this->authenticate($_POST["pseudo"], $_POST['motdepasse']);
		}
		$this->index($route);
	}

	public function delog($route){
		$this->logOut();
		$this->index($route);
	}

	public function cancelAll($route){
		$user = $this->isConnected();
		if($user != -1){
			include("lib/config.php");
			$con = mysql_connect($db_server,$db_user,$db_password);
			if (!$con)
			{
				die('Could not connect: ' .mysql_error());
			}
			mysql_select_db($db_name) or die(mysql_error());

			$reqSql = sprintf("DELETE FROM Bookings WHERE id_user = %d",$user);
			mysql_query($reqSql) or die(mysql_error());
			$this->index($route);
		} else {
			$this->render_error("error", "Not Identified request. You should log in first.", $route);
        }
	}
	
		public function rapport($route){
		$params['controller'] = 'user';
		$this->render_view("rapport",$route);
		
        }
}
?>
